package com.view.cn.mvprxjava.view;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.View;

import com.view.cn.mvprxjava.fragment.PieViewFragment;

import java.util.ArrayList;

/**
 * Created by Zengxiaoping on 2016/11/28.
 */
public class PieView extends View {

	// 颜色表 (注意: 此处定义颜色使用的是ARGB，带Alpha通道的)
	private int[] mColors = {0xFFCCFF00, 0xFF6495ED, 0xFFE32636, 0xFF800000, 0xFF808000, 0xFFFF8C69, 0xFF808080,
			0xFFE6B800, 0xFF7CFC00};
	//饼状图初始绘制角度
	private float mStartAngle = 0;
	//数据
	private ArrayList<PieViewFragment.PieData> mList;
	//宽高
	private int mWidth, mHeight;
	//创建一个画笔
	private Paint mPaint = new Paint();


	public PieView(Context context) {
		super(context);
	}

	public PieView(Context context, AttributeSet attrs) {
		super(context, attrs);
		initPaint();
	}

	private void initPaint() {
		/**
		 * STROKE                //描边
		 * FILL                  //填充
		 * FILL_AND_STROKE       //描边加填充
		 */
		mPaint.setStyle(Paint.Style.FILL);  //设置画笔模式为填充
		mPaint.setColor(Color.BLACK);       //设置画笔颜色
		mPaint.setStrokeWidth(10f);         //设置画笔宽度为10px
		mPaint.setAntiAlias(true);
	}


	@Override
	protected void onSizeChanged(int w, int h, int oldw, int oldh) {
		super.onSizeChanged(w, h, oldw, oldh);
		mWidth = w;
		mHeight = h;
	}

	@Override
	protected void onDraw(Canvas canvas) {
		super.onDraw(canvas);
		if (null == mList)
			return;
		initCanvas(canvas);
	}

	//初始化画板
	private void initCanvas(Canvas canvas) {
		canvas.drawColor(Color.BLUE);

		float currentAngle = mStartAngle;               //当前角度
		canvas.translate(mWidth / 2, mHeight / 2);      //移动画板到中心位置
		float r = (float) (Math.min(mWidth, mHeight) / 2 * 0.8);//取得圆半径
		RectF rectF = new RectF(-r, -r, r, r);
		for (PieViewFragment.PieData data : mList) {    //画一个个的扇形
			mPaint.setColor(data.color);
			canvas.drawArc(rectF, currentAngle, data.angle, true, mPaint);
			currentAngle += data.angle;
		}
	}

	public void setPieData(ArrayList<PieViewFragment.PieData> list) {
		mList = list;
		initData(mList);
		invalidate();
	}

	private void initData(ArrayList<PieViewFragment.PieData> list) {
		if (list == null || list.size() == 0) {
			return;
		}
		float sumValue = 0;
		int i = 0;
		for (PieViewFragment.PieData data : list) {
			sumValue += data.value;
			data.color = mColors[i];             //设置颜色
			i++;
		}

		//计算百分比和对应的角度
		for (PieViewFragment.PieData data : list) {
			float percentage = data.value / sumValue;   //百分比
			float angle = percentage * 360;             //角度

			data.percentage = percentage;
			data.angle = angle;
		}
	}
}
